package com.cmcc.linlaker.ui.query.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.VolleyError;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.cmcc.linlaker.LoginActivity;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.bean.LoginBean;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.query.FarmerDetailActivity;
import com.cmcc.linlaker.ui.query.NewProjectActivity;
import com.cmcc.linlaker.ui.query.ProjectDetailActivity;
import com.cmcc.linlaker.ui.query.ProjectListActivity;
import com.cmcc.linlaker.ui.query.adapter.QueryProjectAdapter;
import com.cmcc.linlaker.ui.query.bean.QueryProjectBean;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.volley.GsonRequestHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProjectFragment extends Fragment {
    private View fragmentView;

    public static ProjectFragment newInstance() {
        ProjectFragment fragment = new ProjectFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_query_project, container, false);
        initView();
        return fragmentView;
    }

    private RecyclerView recycler_project;
    private QueryProjectAdapter adapter;
    private List<QueryProjectBean.QueryProjectData> itemList = new ArrayList<>();

    private MaterialRefreshLayout refreshLayout;

    private void initView() {
        recycler_project = fragmentView.findViewById(R.id.recycler_project);
        setRecyclerView(recycler_project, itemList);

        fragmentView.findViewById(R.id.layout_new_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newUpload();
            }
        });

        refreshLayout = fragmentView.findViewById(R.id.refresh);
        refreshLayout.setLoadMore(true);
        refreshLayout.setWaveShow(true);
        refreshLayout.setWaveColor(Color.parseColor("#3eaefc"));

        refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reset();
                    }
                }, 2000);
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (isHasLoaded) {
                    ToastUtils.showText(getActivity(), "数据已全部加载");
                    refreshLayout.finishRefreshLoadMore();
                } else {
                    getProjectSearchList(projectName, projectCode, things, regionValue, industryValue, usingAttributesValue, departmentValue, true);
                }
            }
        });

        getProjectSearchList("", "", "", "", "", "", "", false);
    }

    private String projectName, projectCode, things, regionValue, industryValue, usingAttributesValue, departmentValue;


    private int pageSize = 20;
    private int pageNum = 1;
    private boolean isHasLoaded = false;

    private void reset() {
        itemList.clear();
        pageNum = 1;
        isHasLoaded = false;
        getProjectSearchList(projectName, projectCode, things, regionValue, industryValue, usingAttributesValue, departmentValue, false);
    }

    /**
     * 新建项目
     */
    private void newUpload() {
        Intent intent = new Intent(getActivity(), NewProjectActivity.class);
        startActivity(intent);
    }

    public static boolean isAddedNew = false;

    @Override
    public void onResume() {
        super.onResume();

        if (isAddedNew) {
            isAddedNew = false;
            getProjectSearchList(projectName, projectCode, things, regionValue, industryValue, usingAttributesValue, departmentValue, false);
        }
    }

    private void setRecyclerView(final RecyclerView recycler_view, final List<QueryProjectBean.QueryProjectData> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));

        recycler_view.setNestedScrollingEnabled(false);
        adapter = new QueryProjectAdapter(getActivity(), itemList);
        adapter.setOnItemClickListener(new QueryProjectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).industry.equals("8")) {
                    //农民建房
                    Intent intent = new Intent(getActivity(), FarmerDetailActivity.class);
                    intent.putExtra("houseData", itemList.get(position));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), ProjectDetailActivity.class);
                    intent.putExtra("projectData", itemList.get(position));
                    startActivity(intent);
                }

            }
        });
        recycler_view.setAdapter(adapter);
    }

    /**
     * 获取项目列表search
     */
    public void getProjectSearchList(String projectName,
                                     String projectCode,
                                     String things,
                                     String regionValue,
                                     String industryValue,
                                     String usingAttributesValue,
                                     String department, boolean isLoaderMore) {
        this.projectName = projectName;
        this.projectCode = projectCode;
        this.things = things;
        this.regionValue = regionValue;
        this.industryValue = industryValue;
        this.usingAttributesValue = usingAttributesValue;
        this.departmentValue = department;

        if (!isLoaderMore) {
            itemList.clear();
            pageNum = 1;
            isHasLoaded = false;
        }

        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();
        params.put("name", projectName);
        params.put("code", projectCode);
        params.put("approvalMatters", things);
        params.put("region", regionValue);
        params.put("industry", industryValue);
        params.put("usingAttributes", usingAttributesValue);
        params.put("deptId", department);
        params.put("projectSort", "0");
        params.put("pageSize", pageSize + "");
        params.put("pageNum", pageNum + "");
        params.put("orderByColumn", "createDate");
        params.put("isAsc", "desc");
        helper.sendPOSTRequest(ApiDefine.PROJECT_LIST10, QueryProjectBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    QueryProjectBean bean = (QueryProjectBean) data;

                    if (bean.code.equals("0")) {
                        List<QueryProjectBean.QueryProjectData> rows = bean.rows;
                        if (rows.size() == pageSize) {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            pageNum++;
                        } else {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            isHasLoaded = true;
                        }
                        refreshLayout.finishRefresh();
                        refreshLayout.finishRefreshLoadMore();

                        if (itemList.size() == 0) {
                            fragmentView.findViewById(R.id.layout_no_data).setVisibility(View.VISIBLE);
                            refreshLayout.setVisibility(View.GONE);
                        } else {
                            fragmentView.findViewById(R.id.layout_no_data).setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                        }

                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(getActivity());
                    } else {
                        ToastUtils.showText(getActivity(), bean.msg);
                    }
                }
            }
        });
    }

    /**
     * 获取项目列表
     */
    public void getProjectList(boolean isShowDialog) {
        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();
        params.put("projectSort", "0");
        params.put("pageSize", pageSize + "");
        params.put("pageNum", pageNum + "");
        params.put("orderByColumn", "createDate");
        params.put("isAsc", "desc");
        helper.sendPOSTRequest(ApiDefine.PROJECT_LIST10, QueryProjectBean.class, params, isShowDialog, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    QueryProjectBean bean = (QueryProjectBean) data;

                    if (bean.code.equals("0")) {
                        List<QueryProjectBean.QueryProjectData> rows = bean.rows;
                        if (rows.size() == pageSize) {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            pageNum++;
                        } else {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            isHasLoaded = true;
                        }
                        refreshLayout.finishRefresh();
                        refreshLayout.finishRefreshLoadMore();
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(getActivity());
                    } else {
                        ToastUtils.showText(getActivity(), bean.msg);
                    }
                }
            }
        });
    }
}
